﻿using System;
using System.Linq;
using Ninject;
using SydEnergiPrototype.Logic;

namespace SydEnergiPrototype.DataAccess
{
    public class DataService : Subject, IDataService
    {
        private readonly IDataRepository _dataRepository;

        [Inject]
        public DataService(IDataRepository repository)
        {
            if(repository == null)
                throw new ArgumentNullException("repository");
            _dataRepository = repository;
        }

        public void RetrieveCabinets(ReturnResult callback)
        {
            _dataRepository.GetCabinetsAsync(callback);
        }

        public void PersistEntry(ReturnResult callback)
        {
            if (string.IsNullOrWhiteSpace(callback.Parameter.CabinetId))
                throw new Exception("No cabinet id associated with entry.");

            _dataRepository.GetCabinetsAsync(new ReturnResult(GetCabinetsCompleted, callback.Parameter));
        }

        private void GetCabinetsCompleted(ReturnResult result)
        {
            var cabinets = result.Result;
            var entry = result.Parameter;

            var cabinet = cabinets.Single(c => c.Id == entry.CabinetId);
            if (cabinet.EntryCollection.Any(e => (e.EntryAddress.Equals(entry.EntryAddress)) && e.CabinetId == entry.CabinetId))
            {
                foreach (var e in cabinet.EntryCollection)
                {
                    if (entry.Equals(e))
                    {
                        var index = cabinet.EntryCollection.IndexOf(e);
                        cabinet.EntryCollection[index] = entry;
                        _dataRepository.SetCabinetsAsync(NotifyObservers, cabinets);
                        return;
                    }
                }
            }

            cabinet.EntryCollection.Add(entry);
            _dataRepository.SetCabinetsAsync(NotifyObservers, cabinets);
        }
    }
}
